using Identity.Application.Contracts.Common;
using Identity.Application.PermissionKeyResourceIds.Commands;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Application.Permissions.Interfaces;
using MediatR;

namespace Identity.Application.PermissionKeyResourceIds.CommandHandlers
{
    public class AssignPermissionCommandHandler : IRequestHandler<AssignPermissionCommand, Result>
    {
        private readonly IApiPermissionBindingRepository _permissionKeyResourceIdRepository;
        private readonly IPermissionsReadService _permissionsReadService;
        private readonly IUnitOfWork _unitOfWork;
        public AssignPermissionCommandHandler(IApiPermissionBindingRepository permissionKeyResourceIdRepository, IPermissionsReadService permissionsReadService, IUnitOfWork unitOfWork)
        {
            _permissionKeyResourceIdRepository = permissionKeyResourceIdRepository;
            _permissionsReadService = permissionsReadService;
            _unitOfWork = unitOfWork;
        }
        public async Task<Result> Handle(AssignPermissionCommand request, CancellationToken cancellationToken)
        {
            var apiPermission = _permissionKeyResourceIdRepository.GetByResourceId(request.resourceId);
            if (apiPermission == null) return Result.Failure($"找不到 ResourceId={request.resourceId} 的接口权限绑定记录");
            var permission = await _permissionsReadService.GetByIdAsync(Guid.Parse(request.permissionId));
            if (permission == null) return Result.Failure($"找不到 permissionKey={request.permissionId} 的权限记录");


            apiPermission.AssignPermission(permission.Id);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return Result.Success(apiPermission);
        }
    }
}